package cn.earas.ip;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;

import cn.earas.ip.frame.LoadingFrame;
import cn.earas.ip.frame.MainFrame;
import cn.earas.ip.frame.OutFrame;
import cn.earas.ip.netdata.IPGet_66;
import cn.earas.ip.netdata.IPGet_89;
import cn.earas.ip.netdata.IPGet_KuaiDaiLi;
import cn.earas.ip.netdata.IPGet_SeoFangFa;
import cn.earas.ip.netdata.IPGet_SupperFast;
import cn.earas.ip.netdata.IPGet_Yqie;

public class DataUtil implements Runnable
{
    int type;
    int threadNum;
    int ms;
    boolean more;
    File file;
    LoadingFrame lf;
    String path;
    String split;
    
    public DataUtil(final int type) {
        this.type = type;
    }
    
    public DataUtil(final int type, final File file, final LoadingFrame lf) {
        this.type = type;
        this.file = file;
        this.lf = lf;
    }
    
    public DataUtil(final int type, final int threadNum, final int ms, boolean more) {
        this.type = type;
        this.threadNum = threadNum;
        this.ms = ms;
        this.more = more;
    }
    
    public DataUtil(final int type, final String path, final String split, final LoadingFrame lf) {
        this.type = type;
        this.path = path;
        this.split = split;
        this.lf = lf;
    }
    
    public void getIPsByInPutFile() {
        int i = 0;
        final List<String> result = new ArrayList<String>();
        try {
            final Scanner sc = new Scanner(this.file);
            String temp = "";
            while (sc.hasNext()) {
                temp = temp + sc.next() + "\r\n";
                if (MainFrame.inFlag) {
                    break;
                }
            }
            sc.close();
            final Matcher m = Pattern.compile(Data.REG).matcher(temp);
            while (m.find()) {
                result.add(m.group(1));
                if (MainFrame.inFlag) {
                    break;
                }
            }
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        final File userFile = new File("user.data");
        if (!userFile.exists() && !MainFrame.inFlag) {
            try {
                userFile.createNewFile();
                final Scanner sc2 = new Scanner(userFile);
                String temp2 = "";
                while (sc2.hasNext()) {
                    temp2 += sc2.next();
                    if (MainFrame.inFlag) {
                        break;
                    }
                }
                sc2.close();
                final PrintWriter pw = new PrintWriter(userFile);
                for (final String temp3 : result) {
                    if (!temp2.contains(temp3)) {
                        pw.write(temp3 + ";");
                        ++i;
                        if (MainFrame.inFlag) {
                            break;
                        }
                        continue;
                    }
                }
                pw.flush();
                pw.close();
            }
            catch (IOException e2) {
                e2.printStackTrace();
            }
        }
        this.lf.dispose();
        if (MainFrame.inFlag) {
            JOptionPane.showMessageDialog(null, "\u5bfc\u5165\u5931\u8d25\uff0c\u7528\u6237\u505c\u6b62\u5bfc\u5165\u64cd\u4f5c", "\u5bfc\u5165\u4fe1\u606f", 2);
        }
        else {
            JOptionPane.showMessageDialog(null, "\u5bfc\u5165\u6210\u529f\uff0c\u5171\u5bfc\u5165" + i + "\u6761\u7ed3\u679c", "\u5bfc\u5165\u4fe1\u606f", 1);
        }
    }
    
    private void outPut() {
        final File file = new File(this.path + "/ip-result.txt");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            final PrintWriter pw = new PrintWriter(file);
            for (DataModel dm : Data.result2) {
                pw.write(dm.getIp() + ":" + dm.getPort() + this.split);
                if (OutFrame.outFlag) {
                    break;
                }
            }
            pw.flush();
            pw.close();
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e2) {
            e2.printStackTrace();
        }
        this.lf.dispose();
        if (OutFrame.outFlag) {
            JOptionPane.showMessageDialog(null, "\u5bfc\u51fa\u5931\u8d25\uff0c\u7528\u6237\u505c\u6b62\u5bfc\u51fa\u64cd\u4f5c\uff01", "\u5bfc\u51fa\u4fe1\u606f", 2);
        }
        else {
            JOptionPane.showMessageDialog(null, "\u5bfc\u51fa\u6210\u529f\uff0c\u4f4d\u7f6e\uff1a" + this.path + "\\ip-result.txt", "\u5bfc\u51fa\u4fe1\u606f", 1);
        }
    }
    
    private void getIPsByUserFile() {
        try {
            final String filePath = System.getProperty("user.dir");
            final File userFile = new File(filePath + "/user.data");
            final Scanner sc = new Scanner(userFile);
            String temp = "";
            while (sc.hasNext() && Data.run) {
                temp += sc.next();
            }
            sc.close();
            final Matcher m = Pattern.compile("((\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\:\\d{1,5})").matcher(temp);
            while (m.find() && Data.run) {
            	String tempStr = m.group(1);
                if(!Data.ips.contains(tempStr)) Data.ips.add(tempStr);
            }
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        --Data.flag;
        MainFrame.jTextArea1.append("\u8bfb\u53d6\u7528\u6237\u6570\u636e\u6e90\u5b8c\u6bd5\u3002\n");
    }
    
    private void getIPsByDataFile() {
        try {
            final InputStream stream = this.getClass().getClassLoader().getResourceAsStream("ips.data");
            final BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            String str = "";
            while ((str = br.readLine()) != null && Data.run) {
            	if(!Data.ips.contains(str)) Data.ips.add(str);
            }
        }
        catch (Exception ex) {}
        --Data.flag;
        MainFrame.jTextArea1.append("\u8bfb\u53d6\u7a0b\u5e8f\u6570\u636e\u6e90\u5b8c\u6bd5\u3002\n");
    }
    
    private void getIPsByNetwork() {
        List<Thread> threads = new ArrayList<Thread>();
        Thread t1 = new Thread(new IPGet_66());
        Thread t2 = new Thread(new IPGet_KuaiDaiLi());
        Thread t3 = new Thread(new IPGet_89());
        Thread t4 = new Thread(new IPGet_SupperFast());
        Thread t5 = new Thread(new IPGet_SeoFangFa());
        Thread t6 = new Thread(new IPGet_Yqie());
        threads.add(t1);
        threads.add(t2);
        threads.add(t3);
        threads.add(t4);
        threads.add(t5);
        threads.add(t6);
        for(Thread t : threads){
        	if(!Data.run) break;
        	t.start();
        }
        while (!threads.isEmpty()) {
            try {
                if(Data.run) threads.remove(0).join();
                else threads.remove(0).join(1);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        --Data.flag;
        MainFrame.jTextArea1.append("读取网络数据源完毕。\n");
    }
    
    private void check() {
        while (Data.flag > 0) {
            try {
                Thread.sleep(1000L);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        final long start = System.currentTimeMillis();
        if(Data.run){
        	MainFrame.jTextArea1.append("\u5f00\u59cb\u68c0\u6d4b\uff0c\u7ebf\u7a0b\u6570\uff1a" + this.threadNum + "\uff0c\u6700\u5927\u54cd\u5e94\u65f6\u95f4\uff1a" + this.ms + "\u6beb\u79d2\u3002\n");
            final List<Thread> threads = new ArrayList<Thread>();
            for (int i = 0; i < this.threadNum; i++) {
                final Thread t = new Thread(new NetCheck(this.ms,this.more,this.threadNum));
                t.start();
                threads.add(t);
            }
            while (!threads.isEmpty()) {
                try {
                    if(Data.run) threads.remove(0).join();
                    else threads.remove(0).join(1);
                }
                catch (InterruptedException e2) {
                    e2.printStackTrace();
                }
//                if(!Data.run) break;
            }
        }
        final long end = System.currentTimeMillis();
        final SimpleDateFormat sdf = new SimpleDateFormat("mm\u5206ss\u79d2SSS\u6beb\u79d2\u3002");
        MainFrame.jTextArea1.append("\u6267\u884c\u5b8c\u6bd5\uff0c\u53ef\u7528\u7ed3\u679c\u6570\uff1a" + Data.result2.size() + "\uff0c\u7528\u65f6\uff1a" + sdf.format(end - start));
        MainFrame.jProgressBar1.setValue(Data.total);
        MainFrame.jProgressBar1.setString("100%");
        MainFrame.jMenuItem1.setEnabled(true);
        MainFrame.jMenuItem2.setEnabled(true);
//        MainFrame.jMenuItem6.setEnabled(true);
        MainFrame.jButton1.setEnabled(true);
        MainFrame.jToggleButton1.setEnabled(false);
        MainFrame.buttonFlag = true;
        MainFrame.jButton1.setText("\u5f00\u59cb");
    }
    
    @Override
    public void run() {
        if (this.type == 1) {
            this.getIPsByDataFile();
        }
        if (this.type == 2) {
            this.getIPsByUserFile();
        }
        if (this.type == 3) {
            this.getIPsByNetwork();
        }
        if (this.type == 4) {
            this.check();
        }
        if (this.type == 5) {
            this.getIPsByInPutFile();
        }
        if (this.type == 6) {
            this.outPut();
        }
    }
}
